package edu.nf.llmtest.service.impl;

import edu.nf.llmtest.common.enumeration.RedisKeyEnum;
import edu.nf.llmtest.service.TokenService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ Author bin
 * @ Create  2025/10/27 上午9:27
 **/
@RequiredArgsConstructor
@Service
public class TokenServiceImpl implements TokenService {
    private final StringRedisTemplate redisTemplate;
    private final long expireSeconds = TimeUnit.DAYS.toSeconds(7L);


    // 生成 token 并存 Redis
    public String createTokenForUser(String email) {
        String token = UUID.randomUUID().toString().replace("-", "");
        String key = RedisKeyEnum.TOKEN_PREFIX.getValue() + token;
        redisTemplate.opsForValue().set(key, email, expireSeconds, TimeUnit.DAYS);
        return token;
    }

    // 根据 token 获取 userId（若不存在则返回 null）
    public String getUserIdByToken(String token) {
        if (token == null) return null;
        return redisTemplate.opsForValue().get(RedisKeyEnum.TOKEN_PREFIX.getValue() + token);
    }

    // 删除 token（登出）
    public void deleteToken(String token) {
        redisTemplate.delete(RedisKeyEnum.TOKEN_PREFIX.getValue() + token);
    }
}
